﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;
using System.IO;
using System.Xml;
using System.Resources;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using InscriberControlServer;

namespace ServiceTemplate
{
    internal class Functionality
    {
        static public INI iniconfig = new INI();
        // static WMEncoderApp EncoderApp;
        static private XmlDocument xDoc = null;
        //static private DataBase dbc = null;
        static StreamWriter Tex;
        static private string dbServer = "localhost\\SQLExpress";
        static private string db = "DB";
        static private string db_user = "";
        static private string db_password = "";
        static private string db_config_tbl = "TB";
        static private string CGServer1 = "127.0.0.1";
        static private string CGPort1 = "50000";
        static private string CGServer2 = "127.0.0.1";
        static private string CGPort2 = "50001";
        static private Timer timerValiutos;
        static private CurrencyCycle currencyRoller;


        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section,
            string key, string val, string filePath);

        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section,
                 string key, string def, StringBuilder retVal,
            int size, string filePath);


        public static void IniWriteValue(string Section, string Key, string Value, string Path)
        {
            WritePrivateProfileString(Section, Key, Value, Path);
        }


        public static string IniReadValue(string Section, string Key, string Path)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, Path);
            return temp.ToString();
        }

        public static string ReadRegistry(RegistryKey baseRegistryKey, string subKey, string KeyName)
        {
            RegistryKey rk = baseRegistryKey; // pav.: Registry.CurrentUser
            RegistryKey sk1 = rk.OpenSubKey(subKey); //pav.:  "SOFTWARE\\MYPROGRAM\\MYSUBKEY"
            if (sk1 == null)
            {
                return null;
            }
            else
            {
                try
                {
                    return (string)sk1.GetValue(KeyName.ToUpper()).ToString();
                }
                catch (Exception e)
                {
                    AddToEventLog("videosource", e.ToString(), true);
                    // MessageBox.Show(e.ToString(), "Reading registry " + KeyName.ToUpper(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return null;
                }
            }
        }

        public static bool WriteRegistry(RegistryKey baseRegistryKey, string subKey, string KeyName, object Value)
        {
            try
            {
                RegistryKey rk = baseRegistryKey;  // pav.: Registry.CurrentUser
                RegistryKey sk1 = rk.CreateSubKey(subKey); //pav.:  "SOFTWARE\\MYPROGRAM\\MYSUBKEY"
                sk1.SetValue(KeyName.ToUpper(), Value);

                return true;
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString(), "Writing registry " + KeyName.ToUpper(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }

        // get service startup path
        public static string StartPath
        {
            get
            {
                return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6);
            }
        }

        public static string ToTime(DateTime tm)
        {
            //tm.To
            string time = "00:00:00";
            string hours = tm.Hour.ToString();
            if (hours.Length == 1)
            {
                hours = "0" + hours;
            }
            string minutes = tm.Minute.ToString();
            if (minutes.Length == 1)
            {
                minutes = "0" + minutes;
            }
            string seconds = tm.Second.ToString();
            if (seconds.Length == 1)
            {
                seconds = "0" + seconds;
            }
            time = hours + ":" + minutes + ":" + seconds;
            return time;
        }

        public static string ToDate(DateTime tm)
        {
            string time = "00:00:00";
            string Years = tm.Year.ToString();
            string Months = tm.Month.ToString();
            if (Months.Length == 1)
            {
                Months = "0" + Months;
            }
            string Days = tm.Day.ToString();
            if (Days.Length == 1)
            {
                Days = "0" + Days;
            }
            time = Years + "-" + Months + "-" + Days;
            return time;
        }
        //get current date
        static public string getDate()
        {
            return ToDate(DateTime.Now);
        }

        //get current Time
        static public string getTime()
        {
            return ToTime(DateTime.Now);
        }

        // read service database connection parameters from xml
        public static void readXMLParameters()
        {
            try
            {
                XmlTextReader textReader = new XmlTextReader(StartPath + "\\config.xml");

                while (textReader.Read())
                {
                    XmlNodeType nType = textReader.NodeType;
                    if (nType == XmlNodeType.Element)
                    {
                        if (textReader.Name.ToString().Equals("DataBaseServer"))
                        {
                            dbServer = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("DataBaseName"))
                        {
                            db = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("DataBaseUser"))
                        {
                            db_user = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("DataBasePassword"))
                        {
                            db_password = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("ConfigTable"))
                        {
                            db_config_tbl = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("CGServer1"))
                        {
                            CGServer1 = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("CGPort1"))
                        {
                            CGPort1 = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("CGServer2"))
                        {
                            CGServer2 = textReader.ReadElementContentAsString();
                        }
                        if (textReader.Name.ToString().Equals("CGPort2"))
                        {
                            CGPort2 = textReader.ReadElementContentAsString();
                        }
                    }
                }
            }
            catch (Exception ex) { AddToEventLog("InscriberControlServer", "XML skaitymo klaida: " + ex.Message, true); }
        }


        //add error to event list
        public static void AddToEventLog(string sSource, string sEvent, bool error)
        {
            string sLog = "Application";

            if (!EventLog.SourceExists(sSource))
                EventLog.CreateEventSource(sSource, sLog);
            if (error)
            {
                EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Error, 0);
            }
            else
            {
                EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Information, 123);
            }

        }

        public static void closeLogFile()
        {
            Tex.Close();
        }

        public static void process()
        {
            Tex = File.CreateText(StartPath + "\\log.txt");
            while (true)
            {
                // Tex.WriteLine("text");
                //Tex.Flush();
                readCommandTable();
                Thread.Sleep(1000);
            }
        }

        public static void processRunningLines()
        {
           // Tex = File.CreateText(StartPath + "\\logRL.txt");
            while (true)
            {
                // Tex.WriteLine("text");
                //Tex.Flush();
                readRLCommandTable();
                Thread.Sleep(1000);
            }
        }

        public static void processLD()
        {
            // Tex = File.CreateText(StartPath + "\\logRL.txt");
            while (true)
            {
                // Tex.WriteLine("text");
                //Tex.Flush();
                readLDCommandTable();
                Thread.Sleep(1000);
            }
        }

        public static void readRLCommandTable()
        {
            iniconfig.readINI();
            string tl = "";
            string globalTl = "";
            try{
            bool run=true;
            
            bool rlinanimation=false;
            string lastlogo = "";
            bool stoping = false;
            DataBase dbc = new DataBase(dbServer, db_user, db_password, db);
            System.Data.DataTable tb = dbc.getTable("select * from StartConf");
           // System.Data.DataTable tblines = dbc.getTable("select * from RunningLines");
            //System.Data.DataTable tblines = tblines = dbc.getTable("SELECT * FROM LIETUVA_RL UNION SELECT * FROM PASAULIS_RL UNION SELECT * FROM VERSLAS_RL UNION SELECT * FROM KRIMINALAI_RL UNION SELECT * FROM SPORTAS_RL ORDER BY sortorder,id asc");
            System.Data.DataTable tblines = tblines = dbc.getTable("SELECT * FROM LIETUVA_RL UNION SELECT * FROM PASAULIS_RL UNION SELECT * FROM VERSLAS_RL UNION SELECT * FROM KRIMINALAI_RL ORDER BY sortorder,id asc");
            System.Data.DataTable tblinesSport = dbc.getTable("SELECT * FROM SPORTS_RL_NEW left join SPORTS_GROUPS on SPORTS_RL_NEW.ordeId=SPORTS_GROUPS.id ORDER BY SPORTS_RL_NEW.id asc");
            //System.Data.DataTable tbvaliutos = dbc.getTable("SELECT * FROM VERSLAS_RL where RL_line like '%valiutos=%' ORDER BY sortorder,id asc");
                if ((tb.Rows.Count > 0) && (tblines.Rows.Count > 0) && tb.Columns.Contains("RL_start"))
            {
                string line = "";
                string end = "";
                string line1 = "";
                string end1 = "";

                string eilutes_start = tb.Rows[0]["RL_start"].ToString();
                string eilutes_intro_template = tb.Rows[0]["RL_intro_template"].ToString();
                string eilutes_intro_duration = tb.Rows[0]["RL_intro_duration"].ToString();
                string eilutes_template = tb.Rows[0]["RL_template"].ToString();
                string eilutes_end_template = tb.Rows[0]["RL_end_template"].ToString();
                string VT_start = tb.Rows[0]["VT_start"].ToString();
                string message = "T\\7\\" + eilutes_template + "\\E\\\\";
                ClientSocket cl = new ClientSocket(new string[] { "-n", CGServer2, "-p", CGPort2 });
                
                int ix = 0;
                int cyclescount = 0;
                if (eilutes_start.Equals("True"))
                {
                    //message = "T\\7\\" + eilutes_intro_template + "\\E\\\\";
                    //cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                    //--------------------------------------------------------------------Paleidziamas vedejo titras---------------------------------------------------------------
                    if (VT_start.Equals("True"))
                    {
                        message = "T\\7\\VT\\E\\\\";
                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                        //AddToEventLog("InscriberControlServer", eilutes_intro_duration, false);
                        Thread.Sleep(iniconfig.vttime);//int.Parse(eilutes_intro_duration));
                    }
                   // message = "T\\14\\E\\\\";
                    //cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                    //--------------------------------------------------------------------Paleidziamas begancios eilutes intro---------------------------------------------------------------
                    // message = "T\\7\\eilutes1n\\E\\\\";
                     //cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                     
                     //AddToEventLog("InscriberControlServer", message, false);
                     //--------------------------------------------------------------------Paleidziamas begancios eilutes headeris LIETUVA--------------------------------------------------------------
                    tl = getNextTitleRL(tblines,tblinesSport, ix, cyclescount);
                    if (!tl.Equals("")) { globalTl = tl; }
                    message = "T\\7\\" + tl + "\\E\\\\";
                    cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                    Thread.Sleep(iniconfig.introtime);
                    //AddToEventLog("InscriberControlServer", message, false);
                    //-----------nauja------------------------------
                    message = "T\\7\\" + tl + "_still\\E\\\\";
                    cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                    //-----------nauja------------------------------
                   
                }

                int count = tblines.Rows.Count + tblinesSport.Rows.Count;

                while (eilutes_start.Equals("True"))
                {
                    tb = dbc.getTable("select * from StartConf");
                    eilutes_start = tb.Rows[0]["RL_start"].ToString();
                    if (eilutes_start.Equals("False"))
                    {
                        stoping = true;
                        break;
                    }
                    cyclescount++;
                    if (ix < count)
                    {
                        //tblines = dbc.getTable("select * from RunningLines");
                        //tblines = dbc.getTable("SELECT * FROM LIETUVA_RL UNION SELECT * FROM PASAULIS_RL UNION SELECT * FROM VERSLAS_RL UNION SELECT * FROM KRIMINALAI_RL UNION SELECT * FROM SPORTAS_RL ORDER BY sortorder,id asc");
                        tblines = dbc.getTable("SELECT * FROM LIETUVA_RL UNION SELECT * FROM PASAULIS_RL UNION SELECT * FROM VERSLAS_RL UNION SELECT * FROM KRIMINALAI_RL ORDER BY sortorder,id asc");
                        tblinesSport = dbc.getTable("SELECT * FROM SPORTS_RL_NEW left join SPORTS_GROUPS on SPORTS_RL_NEW.ordeId=SPORTS_GROUPS.id ORDER BY SPORTS_RL_NEW.id asc");
                        //tbvaliutos = dbc.getTable("SELECT * FROM VERSLAS_RL where RL_line like '%valiutos=%' ORDER BY sortorder,id asc");
                        /* old string param = "";
                        end = tblines.Rows[ix]["RL_end_symbol"].ToString();
                        if (ix < count-1)
                        {
                            line1 = tblines.Rows[ix + 1]["RL_line"].ToString();
                            end1 = tblines.Rows[ix + 1]["RL_end_symbol"].ToString();
                        }
                        else
                        {
                            line1 = tblines.Rows[0]["RL_line"].ToString();
                            end1 = tblines.Rows[0]["RL_end_symbol"].ToString();
                        }*/
                       /* if (end.Equals("##1"))
                        {
                            param = "\\B2\\" + end + "\\B3\\##3";
                        }
                        else if (end.Equals("##2"))
                        {
                            param = "\\B2\\##3\\B3\\" + end;
                        }
                        else
                        {
                            param = "\\B2\\##3\\B3\\##3";
                        }*/
                        if (cyclescount == 1)
                        {
                            //--------------------------------------------sukuriamas begancios eilutes sablonas eilutes2nT pirmame cikle-----------------------------------------------------------
                            // old message = "I\\30\\5\\B1\\" + line + "\\B2\\" + end + "\\\\";
                            line = tblines.Rows[ix]["RL_line"].ToString();
                            // exit message = "I\\30\\5\\B1\\" + line + "\\\\" ;
                           // exit cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                            //old string komanda = "W\\eilutes2nT\\eilutes2n\\"+line+"\\" + end +"\\"+line1+"\\" +end1+ "\\\\";
                            string komanda = "W\\eilutes2nT\\" + globalTl + "_still\\" + line + "\\\\";
                            cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                          //  message = "T\\7\\eilutes2nT\\E\\\\";
                          //  cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                        }
                        else
                        {
                            //------------------------------------------------------------Sekanciuose cikluose atnaujinamas ON-AiR pirmas tagas sablone eilutes2nT----------------------------------------
                            //message = "I\\30\\5\\1\\" + line + "\\2\\" + end + "\\3\\" + line1 + "\\4\\" + end1 + "\\\\";

                            if (ix < tblines.Rows.Count)
                            {
                                line = tblines.Rows[ix]["RL_line"].ToString();
                                string komanda = "W\\eilutes2nT\\" + globalTl + "_still\\" + line + "\\\\";
                                cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                            }
                            else
                            {
                                //AddToEventLog("InscriberControlServer", "Iejo i sporta", false);
                                line = tblinesSport.Rows[ix - tblines.Rows.Count]["textRL"].ToString();
                                string logoname = tblinesSport.Rows[ix - tblines.Rows.Count]["name"].ToString();
                                string team1 = tblinesSport.Rows[ix - tblines.Rows.Count]["team1"].ToString();
                                string score1 = tblinesSport.Rows[ix - tblines.Rows.Count]["score1"].ToString();
                                string team2 = tblinesSport.Rows[ix - tblines.Rows.Count]["team2"].ToString();
                                string score2 = tblinesSport.Rows[ix - tblines.Rows.Count]["score2"].ToString();
                                string logo = "";
                                //AddToEventLog("InscriberControlServer", "logoname:" + logoname, false);
                                if (logoname.Equals(""))
                                {
                                    logo = "D:/InfoTV/! InfoDiena 2013/1. PNG Sequences/SPORTO LOGO/tuscias.png";
                                }
                                else
                                {
                                    logo = "D:/InfoTV/! InfoDiena 2013/1. PNG Sequences/SPORTO LOGO/"+logoname+".png";
                                }
                                //AddToEventLog("InscriberControlServer", "logo:" + logo, false);

                                if (team1.Equals("") && team2.Equals("") && line.Equals(""))
                                {
                                    //sport header
                                    rlinanimation=checkRLout(rlinanimation,lastlogo);
                                    string komanda = "W\\eilutes2nT\\eilutes3n\\" + logo + "\\" + logoname + "\\\\";
                                    cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                                    AddToEventLog("InscriberControlServer", "komanda:" + komanda, false);
                                    
                                }
                                else if (team1.Equals("") && team2.Equals(""))
                                {
                                    //paprasta
                                    if (logo.Contains("tuscias.png"))
                                    {
                                        rlinanimation = checkRLout(rlinanimation, lastlogo);
                                        string komanda = "W\\eilutes2nT\\" + globalTl + "_still\\" + line + "\\" + logo + "\\\\";
                                        cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                                        AddToEventLog("InscriberControlServer", "komanda:" + komanda, false);
                                     }else{
                                        string komanda = "W\\eilutes2nT\\eilutes5n\\" + line + "\\" + logo + "\\\\";
                                        cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                                        rlinanimation=true;
                                        lastlogo = logo;
                                    }
                                }
                                
                                else if (!team1.Equals("") && !team2.Equals(""))
                                {
                                    //rezultatai
                                    //rlinanimation = checkRLout(rlinanimation, lastlogo);
                                    string komanda = "W\\eilutes2nT\\eilutes4n\\" + team1 + "\\" + team2 + "\\" + score1 + "\\" + score2 + "\\" + logo + "\\\\";
                                    cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                                    AddToEventLog("InscriberControlServer", "komanda:" + komanda, false);
                                }

                                
                                  
                            }

                           //mod message = "I\\30\\5\\1\\" + line + "\\\\";
                           //mod cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                        }
                        //AddToEventLog("InscriberControlServer", message, false);
                        //cl = null;

                       

                       
                        //old Thread.Sleep(5000);
                        //mod int tm = getRLDuration(line) + iniconfig.RLtimeCorrection;
                        //AddToEventLog("InscriberControlServer", "Timer:"+tm.ToString(), false);
                        //mod Thread.Sleep(tm);

                        //mod if (cyclescount == 1)
                        //mod {
                            //--------------------------------------------paleidziamas begancios eilutes sablonas eilutes2nT  pirmame cikle-----------------------------------------------------------
                            
                            message = "T\\7\\eilutes2nT\\E\\\\";
                            cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                            //old Thread.Sleep(5000);
                            int tm = getRLDuration(line) + iniconfig.RLtimeCorrection;
                            Thread.Sleep(tm);
                          //mod }


                            count = tblines.Rows.Count + tblinesSport.Rows.Count;
                            tl = getNextTitleRL(tblines, tblinesSport, ix, cyclescount);
                            if (!tl.Equals("")) { globalTl = tl; }
                           /* if ( tl.Contains("pasaulis-verslas"))
                            {
                                //currencyRoller = new CurrencyCycle(CGServer2,CGPort2);
                                //TimerCallback tcb = currencyRoller.Change;
                                //timerValiutos = new Timer(tcb);
                                //timerValiutos.Change(0, 6000);
                                for (int i = 1; i <= 12; i++)
                                {
                                    message = "T\\7\\verslo_valiutos_" + i.ToString() + "\\D\\\\";
                                    cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                    Thread.Sleep(6000);
                                }
                                
                            }
                            if ( tl.Contains("verslas-kriminalai"))
                            {
                                timerValiutos.Dispose();
                            }*/

                            if (!tl.Equals(""))
                            {
                                //----------------------------------------------------------------paleidziamas begancios eilutes headerio animacija LIETUVA,PASAULIS....------------------------------------------
                                message = "T\\7\\" + tl + "\\E\\\\";
                                cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                Thread.Sleep(iniconfig.RLHeaderTimer);

                                if (tl.Contains("pasaulis-verslas"))
                                {
                                    for (int i = 1; i <= 12; i++)
                                    {
                                        message = "T\\7\\verslo_valiutos_" + i.ToString() + "\\E\\\\";
                                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                        Thread.Sleep(6000);
                                        tb = dbc.getTable("select * from StartConf");
                                        eilutes_start = tb.Rows[0]["RL_start"].ToString();
                                        if (eilutes_start.Equals("False"))
                                        {
                                            break;
                                        }
                                    }

                                }
                                else
                                {
                                    //-----------nauja------------------------------
                                    message = "T\\7\\" + tl + "_still\\E\\\\";
                                    cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                    //-----------nauja------------------------------
                                }

                                //AddToEventLog("InscriberControlServer", message, false);
                            }
                        
                        tb = dbc.getTable("select * from StartConf");
                        eilutes_start = tb.Rows[0]["RL_start"].ToString();
                        if (eilutes_start.Equals("False"))
                        {
                            stoping = true;
                            break;
                        }
                        
                        ix++;
                    }
                    else
                    {
                        ix = 0;
                    }

                    stoping = true;
                }
                if (stoping)
                {
                   // message = "T\\14\\D\\\\";
                //    cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                    // Thread.Sleep(500);
                    message = "T\\14\\E\\\\";
                    cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                }
                cl = null;
            }
             }
            catch (Exception ex) { AddToEventLog("InscriberControlServer", "RunningLines lentelės skaitymo klaida: " + ex.Message, true); }
      
        }

        public static bool checkRLout(bool rlin,string logo)
        {
            if (rlin)
            {
                ClientSocket cl = new ClientSocket(new string[] { "-n", CGServer2, "-p", CGPort2 });
                string komanda = "W\\eilutes2nT\\eilutes6n\\" + logo + "\\\\";
                cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                Thread.Sleep(200);
                string message = "T\\7\\eilutes2nT\\E\\\\";
                cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                Thread.Sleep(800);
            }
            return false;
        }

        public static int getRLDuration(string line)
        {
            return (int)Math.Round((decimal)line.Length/20)*1000;
        }

        public static void readLDTRCommandTable()
        {
            try
            {
               DataBase dbcldtr = new DataBase(dbServer, db_user, db_password, db);
                //AddToEventLog("InscriberControlServer", dbServer+" "+db_user+" "+db_password+" "+db, false);
                
                string message = "T\\7\\T0\\C\\\\";
                ClientSocket cl = new ClientSocket(new string[] { "-n", CGServer2, "-p", CGPort2 });
                System.Data.DataTable tb = dbcldtr.getTable("select * from StartConf");
                
                //AddToEventLog("InscriberControlServer", "LDTR prasideda ", false);
                if ((tb.Rows.Count > 0))
                {
                    string line = "";

                    string ld_start = tb.Rows[0]["LD_start"].ToString();
                    string ld_id = tb.Rows[0]["LD_id"].ToString();
                    string ld_current = tb.Rows[0]["LD_current"].ToString();
                    string ld_cnt = tb.Rows[0]["LD_cnt"].ToString();
                    string timer = tb.Rows[0]["Timer"].ToString();
                    System.Data.DataTable tblines = dbcldtr.getTable("select titrai.id as tid,start_time,end_time from titrai left join leads on titrai.report_id=leads.report_id where leads.id=" + ld_id);

                    //AddToEventLog("InscriberControlServer", "Nuskaityta StartConf", false);
                    bool timerstarted = false;
                    bool timerBreak = false;
                    DateTime timerBegin = DateTime.Now;
                    while (true)
                    {
                        try
                        {
                            dbcldtr = new DataBase(dbServer, db_user, db_password, db);
                            tb = dbcldtr.getTable("select * from StartConf");
                            if ((tb.Rows.Count > 0) && tb.Columns.Contains("Timer"))
                            {
                                timer = tb.Rows[0]["Timer"].ToString();
                                ld_start = tb.Rows[0]["LD_start"].ToString();
                                ld_id = tb.Rows[0]["LD_id"].ToString();
                                ld_current = tb.Rows[0]["LD_current"].ToString();
                                ld_cnt = tb.Rows[0]["LD_cnt"].ToString();
                          
                                string titro_id = "0";
                                int titropause = 0;
                                if (timer.ToLower().Equals("false"))
                                {
                                   timerstarted = false;
                                }
                                if (timer.ToLower().Equals("true") && !timerstarted)
                                {
                                    timerBegin = DateTime.Now.AddSeconds(-2);
                                    timerstarted = true;
                                    AddToEventLog("InscriberControlServer", "TimerStart: " + timerBegin.ToString(), false);
                                }
                                if (timer.ToLower().Equals("true"))
                                {
                                    DateTime timerCurrent = DateTime.Now;
                                    tblines = dbcldtr.getTable("select titrai.id as tid,start_time,end_time from titrai left join leads on titrai.report_id=leads.report_id where leads.id=" + ld_id);
                                    //AddToEventLog("InscriberControlServer", "select titrai.id as tid,start_time,end_time from titrai left join leads on titrai.report_id=leads.report_id where leads.id=" + ld_id, false);
                                    for (int y = 0; y < tblines.Rows.Count; y++)
                                    {
                                        string start_time = tblines.Rows[y]["start_time"].ToString();
                                        string end_time = tblines.Rows[y]["end_time"].ToString();
                                        TimeSpan str_timer = new TimeSpan(int.Parse(start_time.Substring(0, 2)), int.Parse(start_time.Substring(3, 2)), int.Parse(start_time.Substring(6, 2)));
                                       // AddToEventLog("InscriberControlServer", "left Side: " + (timerBegin + str_timer).ToString() + " Right side:" + timerCurrent.ToString(), false);
                                        DateTime time1 = timerBegin + str_timer;
                                        if (time1.Hour == timerCurrent.Hour && time1.Minute == timerCurrent.Minute && time1.Second == timerCurrent.Second)
                                        {
                                            AddToEventLog("InscriberControlServer", "TimerBreak: " + timerCurrent.ToString(), false);
                                            timerBreak = true;
                                            titro_id = tblines.Rows[y]["tid"].ToString();
                                            TimeSpan tm1 = new TimeSpan(int.Parse(end_time.Substring(0, 2)), int.Parse(end_time.Substring(3, 2)), int.Parse(end_time.Substring(6, 2)));
                                            TimeSpan tm2 = new TimeSpan(int.Parse(start_time.Substring(0, 2)), int.Parse(start_time.Substring(3, 2)), int.Parse(start_time.Substring(6, 2)));
                                            titropause = (tm1 - tm2).Seconds * 1000;
                                            dbcldtr.sqlExecute("update StartConf set TimerBreak='True' where id=1");
                                        }
                                    }

                                   /* tblines = dbcldtr.getTable("select logos.id as tid,start_time,end_time,reverse from logos left join leads on logos.report_id=leads.report_id where leads.id=" + ld_id);
                                    for (int y = 0; y < tblines.Rows.Count; y++)
                                    {
                                        string start_time = tblines.Rows[y]["start_time"].ToString();
                                        string end_time = tblines.Rows[y]["end_time"].ToString();
                                        
                                        TimeSpan str_timer = new TimeSpan(int.Parse(start_time.Substring(0, 2)), int.Parse(start_time.Substring(3, 2)), int.Parse(start_time.Substring(6, 2)));
                                        TimeSpan end_timer = new TimeSpan(int.Parse(end_time.Substring(0, 2)), int.Parse(end_time.Substring(3, 2)), int.Parse(end_time.Substring(6, 2)));
                                        DateTime time1 = timerBegin + str_timer;
                                        if (time1.Hour == timerCurrent.Hour && time1.Minute == timerCurrent.Minute && time1.Second == timerCurrent.Second)
                                        {
                                            string logo_id = tblines.Rows[y]["tid"].ToString();
                                             string komanda = "T\\\\7\\\\LG" + logo_id + "\\\\A\\\\\\\\";
                                            
                                             dbcldtr.sqlExecute("insert into komandos (komanda,laikas,data) values ('" + komanda + "','','')");
                                        }
                                        DateTime time2 = timerBegin + end_timer;
                                        if (time2.Hour == timerCurrent.Hour && time2.Minute == timerCurrent.Minute && time2.Second == timerCurrent.Second)
                                        {
                                            string logo_id = tblines.Rows[y]["tid"].ToString();
                                            string komanda = "T\\\\14\\\\A\\\\\\\\";
                                            string reverse = tblines.Rows[y]["reverse"].ToString();
                                            if (reverse.Equals("True"))
                                            {
                                                komanda = "T\\\\7\\\\LG" + logo_id + "out\\\\A\\\\\\\\";
                                            }
                                            
                                            dbcldtr.sqlExecute("insert into komandos (komanda,laikas,data) values ('" + komanda + "','','')");
                                        }
                                    }*/
                                }

                                if (timerBreak)
                                {
                                    if (!titro_id.Equals("0"))
                                    {
                                        AddToEventLog("InscriberControlServer", "Titras: " + DateTime.Now.ToString(), false);  
                                        
                                        cl = new ClientSocket(new string[] { "-n", CGServer2, "-p", CGPort2 });
                                        message = "I\\1\\3\\C\\A\\8\\0\\0\\1\\\\";
                                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                        message = "T\\7\\T" + titro_id + "\\C\\\\";
                                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                        Thread.Sleep(titropause);
                                        dbcldtr.sqlExecute("update StartConf set TimerBreak='False' where id=1");
                                        timerBreak = false;
                                       // timerstarted = false;
                                    }
                                }
                            }
                        }
                        catch (Exception ex) { AddToEventLog("InscriberControlServer", "LDTR lentelės skaitymo klaida1: " + ex.Message, true); }
                        Thread.Sleep(1000);

                    }
                }
            }
            catch (Exception ex) { AddToEventLog("InscriberControlServer", "LDTR lentelės skaitymo klaida2: " + ex.Message, true); }
        
        }

        public static void readLDLGCommandTable()
        {
            try
            {
                List<String> LGstarted = new List<string>();
                DataBase dbcldtr = new DataBase(dbServer, db_user, db_password, db);
                //AddToEventLog("InscriberControlServer", dbServer+" "+db_user+" "+db_password+" "+db, false);

                string message = "T\\7\\T0\\C\\\\";
                ClientSocket cl = new ClientSocket(new string[] { "-n", CGServer2, "-p", CGPort2 });
                System.Data.DataTable tb = dbcldtr.getTable("select * from StartConf");

                //AddToEventLog("InscriberControlServer", "LDTR prasideda ", false);
                if ((tb.Rows.Count > 0))
                {
                    string line = "";

                    string ld_start = tb.Rows[0]["LD_start"].ToString();
                    string ld_id = tb.Rows[0]["LD_id"].ToString();
                    string ld_current = tb.Rows[0]["LD_current"].ToString();
                    string ld_cnt = tb.Rows[0]["LD_cnt"].ToString();
                    string timer = tb.Rows[0]["Timer"].ToString();
                    System.Data.DataTable tblines = dbcldtr.getTable("select titrai.id as tid,start_time,end_time from titrai left join leads on titrai.report_id=leads.report_id where leads.id=" + ld_id);

                    //AddToEventLog("InscriberControlServer", "Nuskaityta StartConf", false);
                    bool timerstarted = false;
                    bool timerBreak = false;
                    bool lgstarted = false;
                    DateTime timerBegin = DateTime.Now;
                    while (true)
                    {
                        try
                        {
                            dbcldtr = new DataBase(dbServer, db_user, db_password, db);
                            tb = dbcldtr.getTable("select * from StartConf");
                            if ((tb.Rows.Count > 0) && tb.Columns.Contains("Timer"))
                            {
                                timer = tb.Rows[0]["Timer"].ToString();
                                ld_start = tb.Rows[0]["LD_start"].ToString();
                                ld_id = tb.Rows[0]["LD_id"].ToString();
                                ld_current = tb.Rows[0]["LD_current"].ToString();
                                ld_cnt = tb.Rows[0]["LD_cnt"].ToString();

                                string titro_id = "0";
                                int titropause = 0;
                                if (timer.ToLower().Equals("false"))
                                {
                                    timerstarted = false;
                                    LGstarted.Clear();
                                }
                                if (timer.ToLower().Equals("true") && !timerstarted)
                                {
                                    timerBegin = DateTime.Now;//;.AddSeconds(-2);
                                    timerstarted = true;
                                    //LGstarted.Clear();
                                    AddToEventLog("InscriberControlServer", "TimerStart: " + timerBegin.ToString(), false);
                                }
                                if (timer.ToLower().Equals("true"))
                                {
                                                                       
                                    tblines = dbcldtr.getTable("select logos.id as tid,start_time,end_time,reverse from logos left join leads on logos.report_id=leads.report_id where leads.id=" + ld_id);
                                    //AddToEventLog("InscriberControlServer", "select titrai.id as tid,start_time,end_time from titrai left join leads on titrai.report_id=leads.report_id where leads.id=" + ld_id, false);
                                    int startedCount = 0;
                                    int stopCount = 0;
                                    for (int y = 0; y < tblines.Rows.Count; y++)
                                    {
                                        string start_time = tblines.Rows[y]["start_time"].ToString();
                                        string end_time = tblines.Rows[y]["end_time"].ToString();

                                        TimeSpan str_timer = new TimeSpan(int.Parse(start_time.Substring(0, 2)), int.Parse(start_time.Substring(3, 2)), int.Parse(start_time.Substring(6, 2)));
                                        TimeSpan end_timer = new TimeSpan(int.Parse(end_time.Substring(0, 2)), int.Parse(end_time.Substring(3, 2)), int.Parse(end_time.Substring(6, 2)));
                                        // AddToEventLog("InscriberControlServer", "left Side: " + (timerBegin + str_timer).ToString() + " Right side:" + timerCurrent.ToString(), false);
                                        DateTime time1 = timerBegin + str_timer;
                                        DateTime timerCurrent = DateTime.Now;
                                        if (time1.Hour == timerCurrent.Hour && time1.Minute == timerCurrent.Minute && time1.Second == timerCurrent.Second )
                                        {
                                            AddToEventLog("InscriberControlServer", "Logo start komanda: " + time1.ToLongTimeString(), true);
                                            string logo_id = tblines.Rows[y]["tid"].ToString();

                                            //string channel = dbcldtr.getTable("select Channel from logo_channels where LogoId='' or LogoId='" + logo_id + "' or timeflag=(select min(timeflag) from logo_channels)").Rows[0][0].ToString();
                                            string channel = dbcldtr.getTable("select Channel,LogoId,timeflag from logo_channels where LogoId='' or LogoId='" + logo_id + "' or timeflag=(select min(timeflag) from logo_channels) group by LogoId,timeflag").Rows[0][0].ToString();
                                            string komanda = "T\\7\\LG" + logo_id + "\\" + channel + "\\\\";
                                            if (!LGstarted.Contains(logo_id))
                                            {
                                                cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                                                dbcldtr.sqlExecute("update logo_channels set LogoId='" + logo_id + "', timeflag=CURRENT_TIMESTAMP where Channel='" + channel + "'");
                                                LGstarted.Add(logo_id);
                                            }

                                            
                                            
                                            startedCount++;
                                            //setChanelMix();
                                            // dbcldtr.sqlExecute("insert into komandos (komanda,laikas,data) values ('I\\\\1\\\\1\\\\D\\\\A\\\\8\\\\0\\\\0\\\\1\\\\\\\\','','')");

                                            //dbcldtr.sqlExecute("insert into komandos (komanda,laikas,data) values ('" + komanda + "','','')");
                                        }
                                        DateTime time2 = timerBegin + end_timer;
                                        if (time2.Hour == timerCurrent.Hour && time2.Minute == timerCurrent.Minute && time2.Second == timerCurrent.Second )
                                        {
                                            //AddToEventLog("InscriberControlServer", "Logo stop komanda: " + time2.ToLongTimeString(), true);
                                            string logo_id = tblines.Rows[y]["tid"].ToString();
                                            string komanda = "T\\14\\A\\\\";
                                            string reverse = tblines.Rows[y]["reverse"].ToString();
                                            if (reverse.Equals("True"))
                                            {
                                                
                                                string channel = dbcldtr.getTable("select Channel from logo_channels where LogoId='" + logo_id + "'").Rows[0][0].ToString();

                                                komanda = "T\\7\\LG" + logo_id + "out\\" + channel + "\\\\";
                                                cl.Send(new string[] { "-m", komanda, "-x", komanda.Length.ToString() });
                                                LGstarted.Remove(logo_id);
                                                dbcldtr.sqlExecute("update logo_channels set LogoId='', timeflag=CURRENT_TIMESTAMP where Channel='" + channel + "'");
                                                lgstarted = false;
                                            }
                                            //setChanelMix();
                                            // dbcldtr.sqlExecute("insert into komandos (komanda,laikas,data) values ('I\\\\1\\\\1\\\\D\\\\A\\\\8\\\\0\\\\0\\\\1\\\\\\\\','','')");

                                           // dbcldtr.sqlExecute("insert into komandos (komanda,laikas,data) values ('" + komanda + "','','')");
                                        }
                                    }
                                    if (startedCount > 0) { lgstarted = true; }
                                }

                                
                            }
                        }
                        catch (Exception ex) { AddToEventLog("InscriberControlServer", "LDTR lentelės skaitymo klaida: " + ex.Message, true); }
                        Thread.Sleep(300);

                    }
                }
            }
            catch (Exception ex) { AddToEventLog("InscriberControlServer", "LDTR lentelės skaitymo klaida: " + ex.Message, true); }

        }


        public static void readLDCommandTable()
        {
            try
            {
                bool run = true;
                bool stoping = false;
                DataBase dbc = new DataBase(dbServer, db_user, db_password, db);
                System.Data.DataTable tb = dbc.getTable("select * from StartConf");
                
                if ((tb.Rows.Count > 0) && tb.Columns.Contains("RL_start"))
                {
                    string line = "";

                    string ld_start = tb.Rows[0]["LD_start"].ToString();
                    string ld_id = tb.Rows[0]["LD_id"].ToString();
                    string ld_current = tb.Rows[0]["LD_current"].ToString();
                    string ld_cnt = tb.Rows[0]["LD_cnt"].ToString();
                    string timer = tb.Rows[0]["Timer"].ToString();
                    string message = "T\\7\\LP" + ld_id + "_" + ld_current + "\\C\\\\";
                    ClientSocket cl = new ClientSocket(new string[] { "-n", CGServer2, "-p", CGPort2 });
                    
                    int ix = 0;
                    int cyclescount = 0;
                    int count = int.Parse(ld_cnt);

                   // System.Data.DataTable tblines = dbc.getTable("select titrai.id as tid,start_time,end_time from titrai left join leads on titrai.report_id=leads.report_id where leads.id=" + ld_id);
                    
                    /*    if (eilutes_start.Equals("True"))
                      {
                          message = "T\\7\\" + eilutes_intro_template + "\\B\\\\";
                          cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                          Thread.Sleep(int.Parse(eilutes_intro_duration));
                          message = "T\\7\\" + eilutes_template + "\\B\\\\";
                          cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                          AddToEventLog("InscriberControlServer", message, false);
                          string tl = getNextTitleRL(tblines, ix, cyclescount);
                          message = "T\\7\\" + tl + "\\A\\\\";
                          cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                          AddToEventLog("InscriberControlServer", message, false);
                      }*/

                    bool timerBreak = false;
                    bool breakingcycle=false;
                   /* if (ld_start.Equals("True"))
                    {
                        message = "T\\7\\juosta_paprasta\\C\\\\";
                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                
                    }*/
                    Thread.Sleep(2000);

                    while (ld_start.Equals("True"))
                    {
                        tb = dbc.getTable("select * from StartConf");
                        timerBreak = bool.Parse(tb.Rows[0]["TimerBreak"].ToString());
                        ld_start = tb.Rows[0]["LD_start"].ToString();
                        string ld_id_tmp = ld_id;
                        ld_id = tb.Rows[0]["LD_id"].ToString();
                        ld_current = tb.Rows[0]["LD_current"].ToString();
                        ld_cnt = tb.Rows[0]["LD_cnt"].ToString();
                        if (!ld_id_tmp.Equals(ld_id))
                        {
                            count = int.Parse(ld_cnt);
                            ix = 0;
                        }
                        
                        if (ld_start.Equals("False")) { break; }
                    BreakFl:
                        if (timerBreak)
                        {
                            Thread.Sleep(500);
                            breakingcycle = true;
                           // AddToEventLog("InscriberControlServer", "timerBreak", false);
                        }
                        else
                        {
                            if (breakingcycle)
                            {
                                        
                                cl = new ClientSocket(new string[] { "-n", CGServer2, "-p", CGPort2 });
                                message = "I\\1\\3\\D\\A\\8\\0\\0\\1\\\\";
                                cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                
                                message = "T\\7\\L" + ld_id + "\\C\\\\";
                                cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                //AddToEventLog("InscriberControlServer", message, false);
                                breakingcycle = false;
                                Thread.Sleep(3400);
                                tb = dbc.getTable("select * from StartConf");
                                timerBreak = bool.Parse(tb.Rows[0]["TimerBreak"].ToString());
                                if (timerBreak)
                                {
                                    goto BreakFl;
                                }
                                ld_start = tb.Rows[0]["LD_start"].ToString();

                                ld_id_tmp = ld_id;
                                ld_id = tb.Rows[0]["LD_id"].ToString();
                                ld_current = tb.Rows[0]["LD_current"].ToString();
                                ld_cnt = tb.Rows[0]["LD_cnt"].ToString();
                                if (!ld_id_tmp.Equals(ld_id))
                                {
                                    count = int.Parse(ld_cnt);
                                    ix = 0;
                                }

                                if (ld_start.Equals("False")) { break; }
                                //AddToEventLog("InscriberControlServer", "ciklas:"+ix.ToString(), false);
                                if (ix == 0)
                                {
                                    ix = ix + 1;
                                }
                                else if (ix > count)
                                {
                                    ix = 1;
                                }
                                //AddToEventLog("InscriberControlServer", "ciklas:" + ix.ToString(), false);
                            }
                           // AddToEventLog("InscriberControlServer", "ciklas", false);
                            cyclescount++;
                            if (ix <= count)
                            {
                                if (cyclescount > 1)
                                {
                                    string tl = getNextLD(ld_id, ix, count);
                                    
                                    message = "I\\1\\3\\D\\A\\8\\0\\0\\1\\\\";
                                    cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                    
                                    message = "T\\7\\" + tl + "\\C\\\\";
                                    cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                    //AddToEventLog("InscriberControlServer", message, false);
                                    //cl = null;
                                   // tb = dbc.getTable("select * from StartConf");
                                    
                                    //count = tblines.Rows.Count;
                                    Thread.Sleep(5000);
                                    
                                    /* string tl = getNextLD(ld_id,ix, count);
                                     if (!tl.Equals(""))
                                     {
                                         message = "T\\7\\" + tl + "\\C\\\\";
                                         cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                                         //AddToEventLog("InscriberControlServer", message, false);
                                     }*/
                                }
                                ix++;
                            }
                            else
                            {
                                ix = 0;
                            }
                        }
                        tb = dbc.getTable("select * from StartConf");
                        ld_start = tb.Rows[0]["LD_start"].ToString();
                        ld_id_tmp = ld_id;
                        ld_id = tb.Rows[0]["LD_id"].ToString();
                        ld_current = tb.Rows[0]["LD_current"].ToString();
                        ld_cnt = tb.Rows[0]["LD_cnt"].ToString();
                        if (!ld_id_tmp.Equals(ld_id))
                        {
                            count = int.Parse(ld_cnt);
                            ix = 0;
                            stoping = false;
                        }
                        else
                        {
                            stoping = true;
                        }
                    }
                    if (stoping)
                    {
                        message = "T\\14\\B\\\\";
                        
                        message = "I\\1\\3\\D\\A\\8\\0\\0\\1\\\\";
                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });

                        message = "I\\1\\4\\D\\A\\8\\0\\0\\1\\\\";
                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });

                        if (dbc.getTable("select template from leads where id=" + ld_id).Rows[0][0].ToString().Equals("K"))
                        {
                            message = "T\\7\\karsta_naujiena_out\\B\\\\";
                            // Thread.Sleep(iniconfig.LDHotNewsTimerBefore);
                            cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                            // Thread.Sleep(iniconfig.LDHotNewsTimerAfter);
                        }
                        else
                        {
                            message = "T\\7\\autro_juosta\\D\\\\";
                            cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                        }

                        message = "T\\7\\tuscias\\C\\\\";
                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                        message = "T\\7\\tuscias\\A\\\\";
                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                        message = "T\\7\\tuscias\\B\\\\";
                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                       // Thread.Sleep(200);
                        //message = "T\\14\\C\\\\";

                        
                        
                        // Thread.Sleep(500);
                     /*   message = "T\\14\\B\\\\";
                        cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });*/
                    }
                    cl = null;
                }
            }
            catch (Exception ex) { AddToEventLog("InscriberControlServer", "LD lentelės skaitymo klaida: " + ex.Message, true); }

        }

        public static string getNextLD(string ld_id,int current, int count)
        {
            string rez = "L" + ld_id;
            if (current == 0 )
            {
                rez = "L" + ld_id;
            }
            else
            {
                rez = "LP" + ld_id + "_" + current.ToString();
            }
            return rez;
        }

        public static string getNextTitleRL(System.Data.DataTable tblines, System.Data.DataTable tblinesSport, int ix, int cyclescount)
        {
            string tl = "";
            string nowtype = "";
            string nexttype = "";
            if (ix < tblines.Rows.Count)
            {
                nowtype = tblines.Rows[ix]["RL_type"].ToString();
                nexttype = tblines.Rows[ix]["RL_type"].ToString();
            }
            else
            {
                nowtype = "SPORTAS";
                nexttype = "SPORTAS";
            }
            if (ix + 1 == tblines.Rows.Count + tblinesSport.Rows.Count)
            {
                nexttype = tblines.Rows[0]["RL_type"].ToString();
            }
            else if (ix + 1 >= tblines.Rows.Count)
            {
                nexttype = "SPORTAS"; 
            }
            else
            {
                nexttype = tblines.Rows[ix + 1]["RL_type"].ToString();
            }
            if (nowtype.Equals(nexttype) && ix == 0 && cyclescount==0)
            {
                tl = nowtype.ToLower();
            }
            else if (!nowtype.Equals(nexttype))
            {
                tl = nowtype.ToLower() + "-" + nexttype.ToLower();
            }
            return tl;
        }

        public static string rpl(string str)
        {
            string newstr = "";
            int ix = -1;
            int ex = -1;
            for (int i = 0; i < str.Length; i++)
            {
                
                if ((int)str[i] == 39)
                {
                    ex = i;
                }
               
            }

            if (ex > -1)
            {
                str = str.Replace("'", "''");
                ex = -1;
            }
            newstr = str;
            return newstr;
        }

        public static void readCommandTable(){
            //this.refreshTable();
            try
            {
                DataBase dbc = new DataBase(dbServer, db_user, db_password, db);
                System.Data.DataTable tb = dbc.getTable("select * from komandos order by id asc");
                for (int i = 0; i < tb.Rows.Count; i++)
                {
                    DateTime current = DateTime.Now;
                    string laikas = current.TimeOfDay.ToString().Substring(0, 8);
                    // string laik = m_dtContacts.Rows[i]["laikas"].ToString();
                    if (tb.Columns.Contains("komanda"))
                    {
                        if (tb.Rows[i]["laikas"].ToString().Equals(laikas))
                        {

                            string komanda = tb.Rows[i]["komanda"].ToString();
                            convertcomm(komanda);

                            string query;
                            query = "insert into atliktos (komanda,laikas,data) values ('" + rpl(tb.Rows[i]["komanda"].ToString()) + "','" + laikas + "','" + current.Date.ToString() + "')";
                            dbc.sqlExecute(query);

                            query = "delete from komandos where id='" + tb.Rows[i]["id"].ToString() + "'";
                            dbc.sqlExecute(query);

                        }
                        else if (tb.Rows[i]["laikas"].ToString().Equals(""))
                        {

                            string komanda = tb.Rows[i]["komanda"].ToString();
                            convertcomm(komanda);

                            string query;
                            query = "insert into atliktos (komanda,laikas,data) values ('" + rpl(tb.Rows[i]["komanda"].ToString()) + "','" + laikas + "','" + current.Date.ToString() + "')";
                            dbc.sqlExecute(query);

                            query = "delete from komandos where id='" + tb.Rows[i]["id"].ToString() + "'";
                            dbc.sqlExecute(query);
                        }
                    }
                }
            }
            catch (Exception ex) { AddToEventLog("InscriberControlServer", "Komandų lentelės skaitymo klaida: " + ex.Message, true); }
        }

        public static void convertcomm(string komanda)
        {
            try
            {
                string message = komanda; // "T\\7\\test2\\A\\\\";
                ClientSocket cl = new ClientSocket(new string[] { "-n", CGServer1, "-p", CGPort1 });
                cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
                cl = null;
                Tex.WriteLine(CGServer1 + ":" + CGPort1 + " m=" + message);
                Tex.Flush();
            }
            catch (Exception ex) { AddToEventLog("InscriberControlServer", "TCP komandos siuntimo klaida: " + ex.Message, true); }
        }

        public static void setChanelMix()
        {
            DataBase dbc = new DataBase(dbServer, db_user, db_password, db);
            //string komanda = "T\\\\7\\\\juosta_paprasta_K\\\\C\\\\\\\\";
            string komanda = "I\\\\1\\\\2\\\\D\\\\A\\\\7\\\\0\\\\0\\\\1\\\\\\\\";
            dbc.sqlExecute("insert into komandos (komanda,laikas,data) values ('" + komanda + "','','')");
            komanda = "I\\\\1\\\\3\\\\D\\\\A\\\\7\\\\0\\\\0\\\\1\\\\\\\\";
            dbc.sqlExecute("insert into komandos (komanda,laikas,data) values ('" + komanda + "','','')");
            komanda = "I\\\\1\\\\4\\\\D\\\\A\\\\7\\\\0\\\\0\\\\1\\\\\\\\";
            dbc.sqlExecute("insert into komandos (komanda,laikas,data) values ('" + komanda + "','','')");
        }

    }

    class CurrencyCycle
    {
        private int maxCount=12;
        ClientSocket cl;
        int nr = 0;

        public CurrencyCycle( string CGServer2, string CGPort2)
        {
            //maxCount = count;
            cl = new ClientSocket(new string[] { "-n", CGServer2, "-p", CGPort2 });
        }

        // This method is called by the timer delegate. 
        public void Change(Object stateInfo)
        {
            nr++;
            if (nr > maxCount) nr = 1;
            string message = "T\\7\\verslo_valiutos_" + nr.ToString() + "\\D\\\\";
            cl.Send(new string[] { "-m", message, "-x", message.Length.ToString() });
        }
    }
}
